<template>
  <div>
    <div class="table-operator">
      <a-button v-has="'member:user:add'" type="primary" icon="plus" @click="openUserInfo()">新增用户</a-button>
      <a-button v-has="'member:user:import'" type="primary" ghost @click="openImportUser">导入用户</a-button>
    </div>
    <div class="table-page-search _p-10 _mb-10" style="background-color: #F7F8FA;">
      <div class="statisticsBox" :class="{ checked: !queryParam.applyType.length }" @click="handChangeApplyType([])">
        <div>全部用户</div>
        <div class="fz-24 fw-6">{{ memberStatistics.userNumber | NumberFormat }}</div>
      </div>
      <div
        class="statisticsBox"
        v-for="dict in Dict.getLocal('applyTypeDict')"
        :key="dict.dictValue"
        :class="{ checked: queryParam.applyType.includes(dict.dictValue) }"
        @click="handChangeApplyType([dict.dictValue])"
      >
        <div>{{ dict.dictLabel }}</div>
        <div v-if="dict.dictValue === 0" class="fz-24 fw-6">
          {{ memberStatistics.nonmemberUserNumber | NumberFormat }}
        </div>
        <div v-if="dict.dictValue === 1" class="fz-24 fw-6">
          {{ memberStatistics.companyUserNumber | NumberFormat }}
        </div>
        <div v-if="dict.dictValue === 2" class="fz-24 fw-6">{{ memberStatistics.personUserNumber | NumberFormat }}</div>
      </div>
      <a-form>
        <a-form-item label="关键词:">
          <a-input v-model="queryParam.keyword" placeholder="姓名/单位/手机号/单位职务" allowClear />
        </a-form-item>
        <a-form-item label="排序方式:">
          <a-select v-model="queryParam.orderByColumn" class="min-width-17" placeholder="请选择排序方式" allowClear>
            <a-select-option value="levelSort">按会员职务排序</a-select-option>
            <a-select-option value="createTime">按创建时间排序</a-select-option>
            <a-select-option value="loginDate">按最近登录时间排序</a-select-option>
          </a-select>
        </a-form-item>
        <span class="search-submitButtons">
          <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
          <a-button type="link" @click="handleReset">重置筛选条件</a-button>
        </span>
      </a-form>
    </div>
    <div class="table-operator disFlxJS">
      <div class="disFlxAC">
        <span class="_pr-10 _pb-10 color9"
          >已勾选<span class="colorZS _pl-2 _pr-2 fw-7">{{ selectedRowKeys.length }}</span
          >位用户</span
        >

        <a-button v-if="total" type="primary" ghost @click="checkedAllUserList"
          >{{ isAllChecked ? '取消勾选' : '勾选' }}"筛选条件"下全部<span class="fw-7 _pl-2 _pr-2">{{ total }}</span
          >位用户</a-button
        >
      </div>

      <div>
        <a-button v-has="'member:user:labelling'" type="primary" ghost @click="openBatchAddTag">批量打标签</a-button>
        <SendMessageSelect
          v-has="'member:user:send'"
          :dataSource="DataSourceEnum.USERLIST"
          :pageSelectedObj="pageSelectedObj"
        />
        <a-button v-has="'member:user:export'" type="primary" ghost :loading="excelLoading" @click="userExport">{{
          excelLoading ? '导出中...' : '导出用户'
        }}</a-button>
      </div>
    </div>

    <STable
      ref="table"
      size="default"
      rowKey="id"
      :columns="newColumns"
      :data="loadData"
      :rowSelection="
        isAllChecked
          ? { fixed: true, selectedRowKeys: selectedRowKeys, getCheckboxProps: getCheckboxProps }
          : { fixed: true, selectedRowKeys: selectedRowKeys, onChange: onSelectChange }
      "
    >
      <!-- 序号 -->
      <template slot="serial" slot-scope="text, record, index">
        {{ (queryParam.current - 1) * queryParam.size + parseInt(index) + 1 }}
      </template>
      <!-- 用户信息 -->
      <template slot="userInfo" slot-scope="text, record, index">
        <div class="disFlxAC">
          <a-avatar size="default" icon="user" :src="record.avatar" />
          <div class="_pl-10 fz-12">
            <div>
              <span>{{ record.name || record.userName }}</span>
            </div>
            <!-- <span v-show="record.name && record.userName && record.name !== record.userName"
                >({{ record.userName }})</span
              > -->
            <div>{{ record.phone }}</div>
          </div>
        </div>
      </template>
      <!-- 单位身份 -->
      <template slot="memberRoleTypeFilter" slot-scope="text, record, index">
        <FilterCheckbox
          v-model="queryParam.memberRoleType"
          :options="
            Dict.getLocal('companyIdentityDict').map(v => {
              return { value: v.dictValue, label: v.dictLabel }
            })
          "
          @search="$refs.table.refresh(true)"
        />
      </template>
      <template slot="memberRoleType" slot-scope="text, record, index">
        <DictTag :options="Dict.getLocal('companyIdentityDict')" :value="text" isText showBorder />
      </template>
      <template slot="reviewQrCode" slot-scope="text, record, index">
        <viewer v-if="text" class="viewer" ref="viewer" :images="[text]">
          <img :src="text" class="viewer-img" style="width:64px;height:64px;" />
        </viewer>
      </template>

      <!-- 用户类型 -->
      <template slot="applyTypeFilter" slot-scope="text, record, index">
        <FilterCheckbox
          v-model="queryParam.applyType"
          :options="
            Dict.getLocal('applyTypeDict').map(v => {
              return { value: v.dictValue, label: v.dictLabel }
            })
          "
          @search="$refs.table.refresh(true)"
        />
      </template>
      <template slot="applyType" slot-scope="text, record, index">
        <DictTag :options="Dict.getLocal('applyTypeDict')" :value="text" isText showBorder />
      </template>
      <!-- 会员职务 -->
      <template slot="levelNameFilter" slot-scope="text, record, index">
        <FilterCheckbox
          v-model="queryParam.levelId"
          :options="
            memberLevelOption.map(v => {
              return { value: v.id, label: v.name }
            })
          "
          @search="$refs.table.refresh(true)"
        />
      </template>
      <!-- 标签 -->
      <template slot="tagUserList" slot-scope="text, record, index">
        <TableTagList :tagList="record.tagUserList" @close="tag => removeTag(record, tag)" />
      </template>
      <!-- 来源渠道 -->
      <template slot="dataSourceFilter" slot-scope="text, record, index">
        <FilterCheckbox
          v-model="queryParam.dataSource"
          :options="[
            { value: 'MINI', label: '小程序' },
            { value: 'PCIMPORT', label: '后台导入' }
          ]"
          @search="$refs.table.refresh(true)"
        />
      </template>
      <template slot="dataSource" slot-scope="text, record, index">
        {{ text === 'MINI' ? '小程序' : '后台导入' }}
      </template>
      <!-- 小程序登录 -->
      <template slot="isLoginFilter" slot-scope="text, record, index">
        <FilterCheckbox
          v-model="queryParam.isLogin"
          :options="
            Dict.getLocal('isLoginDict').map(v => {
              return { value: v.dictValue, label: v.dictLabel }
            })
          "
          @search="$refs.table.refresh(true)"
        />
      </template>
      <template slot="isLogin" slot-scope="text, record, index">
        <DictTag :options="Dict.getLocal('isLoginDict')" :value="text" isText />
      </template>
      <!-- 公众号关注状态 -->
      <template slot="isOfficialAccountFilter" slot-scope="text, record, index">
        <FilterCheckbox
          v-model="queryParam.isOfficialAccount"
          :options="
            Dict.getLocal('isOfficialAccountDict').map(v => {
              return { value: v.dictValue, label: v.dictLabel }
            })
          "
          @search="$refs.table.refresh(true)"
        />
      </template>
      <template slot="dataValueRateFilter" slot-scope="text, record, index">
        <div style="background-color: white;padding: 10px;">
          <a-input-number v-model="queryParam.beginDataIntegrity" :max="100" :min="0" /> % -
          <a-input-number v-model="queryParam.endDataIntegrity" :max="100" :min="0" /> %
          <div style="display: flex;justify-content: end;margin-top: 10px;">
            <a-button type="primary" size="small" @click="$refs.table.refresh(true)">搜索</a-button>
            <a-button size="small" class="_ml-8" @click="handleReset">重置</a-button>
          </div>
        </div>
      </template>
      <template slot="isOfficialAccount" slot-scope="text, record, index">
        <DictTag :options="Dict.getLocal('isOfficialAccountDict')" :value="text" isText />
      </template>
      <!-- 操作 -->
      <div slot="actionFilterIcon" class="disFlxAC min-width-12">
        <CustomTable :name="$route.name" :columns="columns" :newColumns="newColumns" />
      </div>
      <template slot="actionFilter">
        <div></div>
      </template>
      <template slot="action" slot-scope="text, record">
        <ButtonGroup :max-length="3">
          <a-button
            v-for="item in _btnList(record)"
            :key="item.text"
            :type="item.type"
            :ghost="item.ghost"
            size="small"
            class="width-8"
            @click="item.fn"
          >
            {{ item.text }}
          </a-button>
        </ButtonGroup>
      </template>
    </STable>

    <div>
      <!-- 新增 || 编辑用户 -->
      <EditUserInfo ref="EditUserInfo" @refresh="handleReload" />
      <!-- 设为会员 || 关联会员 -->
      <EditMembership ref="EditMembership" :memberLevelOption="memberLevelOption" @refresh="handleReload" />
      <!-- 导入用户 -->
      <UserImport ref="UserImport" @success="handleReload" />
      <!-- 打标签 -->
      <Labelling ref="Labelling" @refresh="handleReload" />
    </div>
  </div>
</template>

<script>
import { STable } from '@/components'
import FilterCheckbox from '@/components/Table/filterCheckbox'
import { getUserList, getUserStatistics, getUserDetail, userExportExcel, checkedAllUser } from '@/api/member/user'
import { memberLevelGetDownList, MemberInfoSearchVoList } from '@/api/system/system'
import EditUserInfo from '@/components/UserComponents/editInfo.vue'
import EditMembership from '@/components/UserComponents/editMembership.vue'
import { mimeMap, readAsText, resolveBlob } from '@/utils/download'
import UserImport from './userImport'
import Labelling from '@/views/member/grouping/components/labelling'
import { batchAssignTag, getBatchUserTag } from '@/api/member/grouping'
import SendMessageSelect from '@/views/operations/message/components/sendMessageSelect'
import { DataSourceEnum } from '@/enums/member'
import { checkPermission } from '@/utils/authority'
import CustomTable from '@/components/Cuscolumn'
import TableTagList from '@/views/member/grouping/components/tableTagList'
import DictTag from '@/components/DictTag'
import ButtonGroup from '@/components/Table/buttonGroup'

export default {
  components: {
    STable,
    FilterCheckbox,
    EditUserInfo,
    EditMembership,
    UserImport,
    Labelling,
    SendMessageSelect,
    CustomTable,
    TableTagList,
    DictTag,
    ButtonGroup
  },
  computed: {
    newColumns() {
      const currentColumns = this.$store.state.user.customTable
      if (currentColumns && currentColumns[this.$route.name]) {
        return this.$options
          .data()
          .columns.filter(v => {
            const _items = currentColumns[this.$route.name].find(item => item === v.title || item.title === v.title)
            if (_items) return Object.assign(v, _items)
          })
          .sort((a, b) => {
            return a.tableSort - b.tableSort
          })
      } else {
        return this.columns
      }
    }
  },
  data() {
    return {
      DataSourceEnum,
      queryParam: {
        beginDataIntegrity: undefined,
        endDataIntegrity: undefined,
        current: 1,
        size: 10,
        keyword: '',
        memberRoleType: [],
        applyType: [],
        levelId: [],
        dataSource: [],
        isLogin: [],
        isOfficialAccount: [],
        orderByColumn: 'createTime' // 排序方式
      },
      total: 0,
      isAllChecked: false,
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' },
          width: '70px'
        },
        {
          title: '用户信息',
          dataIndex: 'userInfo',
          width: '200px',
          ellipsis: true,
          scopedSlots: { customRender: 'userInfo' },
          align: 'left'
        },
        {
          title: '所在单位',
          dataIndex: 'companyName',
          width: '200px',
          ellipsis: true
        },
        {
          title: '单位职务',
          dataIndex: 'companyPositionName',
          width: '120px',
          ellipsis: true
        },
        {
          title: '单位身份',
          dataIndex: 'memberRoleType',
          width: '120px',
          scopedSlots: {
            customRender: 'memberRoleType',
            filterDropdown: 'memberRoleTypeFilter'
          }
        },
        {
          title: '用户类型',
          dataIndex: 'applyType',
          width: '120px',
          scopedSlots: {
            customRender: 'applyType',
            filterDropdown: 'applyTypeFilter'
          }
        },
        {
          title: '会员职务',
          dataIndex: 'levelName',
          width: '120px',
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'levelNameFilter'
          },
          short: true
        },
        {
          title: '用户标签',
          dataIndex: 'tagUserList',
          width: '220px',
          scopedSlots: { customRender: 'tagUserList' }
        },
        {
          title: '主页二维码',
          dataIndex: 'reviewQrCode',
          width: '220px',
          scopedSlots: { customRender: 'reviewQrCode' }
        },
        {
          title: '资料完善度（%）',
          dataIndex: 'dataValueRate',
          width: '220px',
          scopedSlots: {
            filterDropdown: 'dataValueRateFilter'
          }
        },

        {
          title: '小程序',
          dataIndex: 'isLogin',
          width: '120px',
          scopedSlots: {
            customRender: 'isLogin',
            filterDropdown: 'isLoginFilter'
          }
        },
        {
          title: '公众号',
          dataIndex: 'isOfficialAccount',
          width: '140px',
          scopedSlots: {
            customRender: 'isOfficialAccount',
            filterDropdown: 'isOfficialAccountFilter'
          }
        },
        {
          title: '首次来源渠道',
          dataIndex: 'dataSource',
          width: '130px',
          scopedSlots: {
            customRender: 'dataSource',
            filterDropdown: 'dataSourceFilter'
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: '150px',
          ellipsis: true
        },
        {
          title: '最后登录时间',
          dataIndex: 'loginDate',
          width: '150px',
          ellipsis: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          scopedSlots: {
            customRender: 'action',
            filterDropdown: 'actionFilter',
            filterIcon: 'actionFilterIcon'
          },
          width: '266px'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.queryParam.current = parameter.pageNum
        this.queryParam.size = parameter.pageSize
        this.getUserStatisticsNum()
        return getUserList({ ...this.queryParam }).then(res => {
          this.total = res.data.total
          return res
        })
      },
      memberStatistics: {}, // 用户数量统计
      memberLevelOption: [],
      excelLoading: false, // 导出按钮loading
      selectedRowKeys: [],
      // 发送消息所需对象
      pageSelectedObj: {}
    }
  },
  created() {
    this.getUserStatisticsNum()
    this.handelMemberLevelGetDownList()
    // this.columns[this.columns.length - 1].colSpan = 0
    // this.columns[this.columns.length - 1].width = 0
    // this.columns[this.columns.length - 1].fixed = '-'
  },
  methods: {
    handleReset() {
      Object.assign(this.$data.queryParam, this.$options.data().queryParam)
      this.$refs.table.refresh(true)
      this.isAllChecked = false
      this.selectedRowKeys = []
      this.pageSelectedObj = {}
    },

    getUserStatisticsNum() {
      getUserStatistics().then(res => {
        this.memberStatistics = res.data
      })
    },
    handChangeApplyType(selected) {
      this.queryParam.applyType = selected
      this.$refs.table.refresh(true)
    },
    // 会员职务下拉
    handelMemberLevelGetDownList() {
      memberLevelGetDownList().then(res => {
        this.memberLevelOption = res.data
      })
    },
    openUserInfo(row) {
      this.$refs.EditUserInfo.show(row)
    },
    handleReload() {
      this.$refs.table.refresh()
    },
    // 导出用户
    async userExport() {
      try {
        this.excelLoading = true
        let res = await userExportExcel(this.queryParam)
        resolveBlob(res, mimeMap.xlsx)
        this.excelLoading = false
      } catch (error) {
        this.excelLoading = false
      }
    },
    // 导入用户
    openImportUser() {
      this.$refs.UserImport.show()
    },
    // 删除单个标签
    removeTag(row, tag) {
      let params = {
        appUserInfoIdList: [row.id],
        cancelTagIdList: [tag.id]
      }
      batchAssignTag(params).then(() => {
        this.handleReload()
      })
    },
    // 表格数据选中事件
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys

      this.pageSelectedObj[this.queryParam.current] = selectedRows.map(item => {
        return {
          userId: item.smsUserId,
          companyName: item.companyName,
          userName: item.name,
          phone: item.phone,
          companyPosition: item.companyPositionName,
          isOfficialAccount: item.isOfficialAccount,
          applyType: item.applyType
        }
      })
    },
    // 当前筛选条件,全部勾选
    async checkedAllUserList() {
      this.isAllChecked = !this.isAllChecked
      if (this.isAllChecked) {
        const { data } = await checkedAllUser(this.queryParam)
        this.selectedRowKeys = data.appUserInfoIds
        // 获取发送消息所需对象
        MemberInfoSearchVoList({
          dataSource: this.DataSourceEnum.USERLIST,
          userIds: data.smsUserIds,
          current: 1,
          size: data.smsUserIds.length
        }).then(res => {
          this.pageSelectedObj = { 1: res.data.records }
        })
      } else {
        this.selectedRowKeys = []
        this.pageSelectedObj = {}
      }
    },
    getCheckboxProps() {
      return {
        props: {
          disabled: true
        }
      }
    },
    // 批量打标签弹窗打开
    async openBatchAddTag() {
      if (!this.selectedRowKeys.length) {
        this.$message.error('请勾选将要操作的用户')
        return
      }
      const { data } = await getBatchUserTag(this.selectedRowKeys)
      this.$refs.Labelling.show(this.selectedRowKeys, data)
    },
    _btnList(record) {
      let oldList = [
        {
          show: checkPermission('member:user:labelling'),
          text: '打标签',
          type: 'primary',
          ghost: true,
          fn: () => {
            const tagIds = record.tagUserList ? record.tagUserList.map(v => v.id) : []
            this.$refs.Labelling.show([record.id], tagIds)
          }
        },
        {
          show: checkPermission('member:user:relevance'),
          text: record.memberId ? '会员信息' : '设为会员',
          type: record.memberId ? 'default' : 'primary',
          ghost: record.memberId ? false : true,
          fn: () => {
            if (record.memberId) {
              this.$router.push({
                path: '/member/headquartersInfo',
                query: {
                  id: record.memberId
                }
              })
            } else {
              this.$refs.EditMembership.show(record)
            }
          }
        },
        {
          show: checkPermission('member:user:edit'),
          text: '个人信息',
          type: 'warning',
          fn: () => {
            getUserDetail(record.id).then(res => {
              const { data } = res
              this.openUserInfo(data)
            })
          }
        }
      ]
      return oldList.filter(v => v.show)
    }
  }
}
</script>

<style lang="less" scoped></style>
